package com.java.test.encrypt.digest;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.util.encoders.Hex;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author TonyOne
 * @version 1.0
 * @desc
 * @date 2018/9/28 18:29
 * @company
 */
public class SHA {

    public static void SHA256() throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        String text = "abcdfgsgsfd";
        byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
        String encode = new String(Hex.encode(hash));
        System.out.println(encode);
        System.out.println(encode.length());
        String base64 = new String(Base64.encodeBase64(encode.getBytes()),StandardCharsets.UTF_8);
        System.out.println(base64);
        String decode = new String(Base64.decodeBase64(base64),StandardCharsets.UTF_8);
        System.out.println(decode);
    }

    public static void Md5() throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        String text = "abcdfgsgsfd";
        byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
        String encode = new String(Hex.encode(hash));
        System.out.println(encode);
        System.out.println(encode.length());
//        String base64 = new String(Base64.encodeBase64(hash),StandardCharsets.UTF_8);
//        System.out.println(base64);
//        String decode = new String(Base64.decodeBase64(base64),StandardCharsets.UTF_8);
//        System.out.println(decode);

    }

    public static void SHA224() throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-224");
        String text = "abcdefgafgahtus记录囧";
        byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
        String encode = new String(Hex.encode(hash));
        System.out.println(encode);
        System.out.println(encode.length());
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        SHA256();
        //SHA224();
//        Md5();
    }
}
